<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>出租房源</span>
      </div>
      <!-- 搜索表单 -->
      <el-form :model="searchForm" label-width="80px" style="margin-top: 20px;">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="小区名称">
              <el-select
                  v-model="searchForm.communityId"
                  placeholder="请选择小区"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in ComListOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="居室描述" prop="description">
              <el-select
                  v-model="searchForm.description"
                  placeholder="请输入居室描述"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in housewearOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="价格范围">
              <el-select
                  v-model="searchForm.price"
                  placeholder="请选择价格范围"
              >
                <el-option label="≤20万" value="7" />
                <el-option label="20万-25万" value="1" />
                <el-option label="25万-30万" value="2" />
                <el-option label="30万-35万" value="3" />
                <el-option label="35万-40万" value="4" />
                <el-option label="40万-50万" value="5" />
                <el-option label="≥50万" value="6" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="房屋面积">
              <el-select
                  v-model="searchForm.area"
                  placeholder="请选择房屋面积"
              >
                <el-option label="≤50㎡" value="7" />
                <el-option label="50㎡ - 70㎡" value="1" />
                <el-option label="70㎡ - 80㎡" value="2" />
                <el-option label="80㎡ - 90㎡" value="3" />
                <el-option label="90㎡ - 100㎡" value="4" />
                <el-option label="100㎡ - 150㎡" value="5" />
                <el-option label="≥150㎡" value="6" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="housesList">搜索</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="clearsearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <!-- 表格内容 -->
    <el-table :data="houseListData" style="width: 100%" v-loading="loading">
      <el-table-column label="序号" width="60" type="index" />
      <el-table-column label="封面" prop="cover" width="120">
        <template #default="{ row }">
          <el-image
              style="width: 80px; height: 80px; border-radius: 4px;"
              :src="row.cover"
              v-if="row.cover"
              fit="cover"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <span v-else>无封面</span>
        </template>
      </el-table-column>
      <el-table-column label="面积" prop="area" width="70">
        <template #default="{ row }">
          {{ row.area }}㎡
        </template>
      </el-table-column>
      <el-table-column label="价格" prop="price">
        <template #default="{ row }">
          ¥{{ row.price.toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="居室描述" prop="descriptionName" width="120" />
      <el-table-column label="地址" prop="address" />
      <el-table-column label="小区" prop="communityName" />
      <el-table-column label="状态">
        <template #default="{ row }">
          <el-tag
              :type="{
              0: 'warning',
              1:'success',
              2: 'info',
              3: ''
            }[row.status]"
          >
            {{
              {
                0: '待审核',
                1: '已发布',
                2: '已下架',
                3: '已成交'
              }[row.status]
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布日期" prop="publishTime" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
              :icon="Document"
              circle
              plain
              type="info"
              @click="handleEdit(row)"
          />
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无房源数据" />
      </template>

    </el-table>

    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />


    <router-view></router-view>

  </el-card>

</template>

<script setup>
import { Edit, Delete, Document } from '@element-plus/icons-vue'
import {computed, ref, watch} from 'vue'
import {
  addLanHouseService,
  updateHouseService,
  deleteHouseService,
  ReshousesListService
} from '@/api/housesList.js'
import { getHousewearList } from '@/api/housewear'
import { getLanList, getIntList, getCusList } from "@/api/user.js";
import { getCommunityList } from '@/api/community.js';
import { ElMessage, ElMessageBox } from "element-plus";
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {useTokenStore} from "@/stores/token.js";
const tokenStore = useTokenStore();
import { useUserInfoStore } from "@/stores/userinfo.js"
const userInfoStore = useUserInfoStore()

import {useRoute, useRouter} from 'vue-router'
const route = useRoute()
const communityId = route.params.communityId
console.log("route.params.communityId="+communityId)


const userinfoId = userInfoStore.info.id;
console.log("当前用户的id是"+userinfoId)
// 房源列表数据模型
const houseListData = ref([])
// 标题显示
const titleView = ref('');
// 添加数据模型
const HousesModel = ref({
  cover:'',
  remake:'',
  id: '',
  landlordId: '',
  address: '',
  customerId: '',
  area: '',
  price: '',
  description: '',
  type: '',
  status: '',
  communityId: '',
  intermediaryId: '',
  landlordName: '',
  intermediaryName: '',
  communityName: '',
  descriptionName: '',
  customerName: '',
  title:''
})
// 添加表单校验规则
const rules = {
  address: [
  ]
}

// 其他下拉选项数据模型
const housewearOptions = ref([])
const ComListOptions = ref([])

// 分页条数据模型
const pageNum = ref(1) // 当前页
const total = ref(0) // 总条数
const pageSize = ref(15) // 每页条数

// 搜索条件数据模型
const searchForm = ref({
  customerId: '',
  landlordId: '',
  intermediaryId: '',
  communityId: '',
  description: '',
  area: '',
  price: '',
  status:''
})

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  // 重新获取数据
  housesList()
}
// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  // 重新获取数据
  housesList()
}
const loading = ref(false);
// 获取房源列表数据
const housesList = async () => {
  try {
    if (communityId===' '){

    }else {
      searchForm.value.communityId=communityId
    }
    const result = await ReshousesListService({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...searchForm.value // 传递搜索条件
    });
    if (result && result.res) {
      houseListData.value = result.res.items;
      total.value = result.res.total;
      total.value = result.res.total;
    } else {
      console.error('接口返回数据格式不正确，缺少 data 属性');
      ElMessage.error('加载房源列表失败，接口返回数据格式不正确');
    }
  } catch (error) {
    console.error('数据获取失败:', error)
    ElMessage.error('加载房源列表失败')
  }finally {
    loading.value = false; // 结束加载
  }
}

const clearsearch=()=>{
  searchForm.value={
    customerId: '',
    landlordId: '',
    intermediaryId: '',
    communityId: '',
    description: '',
    area: '',
    price: '',
    status:''
  }
  housesList()
}

// 获取其他下拉选项数据
const fetchDropdownOptions = async () => {
  try {
    const reshouse = await getHousewearList()
    housewearOptions.value = reshouse.res.map(item => ({
      value: item.id,
      label: item.houseType
    }))
    const resCom = await getCommunityList()
    ComListOptions.value = resCom.res.map(item => ({
      value: item.id,
      label: item.name
    }))
  } catch (error) {
    console.error('获取失败:', error)
    ElMessage.error('加载失败')
  }
}

fetchDropdownOptions()
housesList()

// 处理查看操作
const router = useRouter()
const handleEdit = (row) => {
  let IntType= "0";
  if (row.status=== "0"){
    IntType= "1";
  }
  router.push({
    name: 'housesItemDetailIntRes',
    params: { id: row.id , IntType:IntType},
  })
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .el-tag {
    margin: 2px;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>

